package com.ruoyi.team.service.impl;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.team.domain.*;
import com.ruoyi.team.service.*;
import com.ruoyi.workflow.domain.BusStoreInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.team.mapper.StockBillMapper;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.Exceptions;

/**
 * 出入库单据Service业务层处理
 *
 * @author ruoyi
 * @date 2022-11-28
 */
@Service
public class StockBillServiceImpl extends ServiceImpl<StockBillMapper, StockBill> implements IStockBillService {

    @Autowired
    private IStoreService storeService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private StockBillMapper stockBillMapper;
    @Autowired
    private IStockBillItemService stockBillItemService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IGoodsStoreService goodsStoreService;
    /**
     * 查询出入库单据列表
     *
     * @param stockBill 出入库单据
     * @return 出入库单据
     */
    @Override
    public List<StockBill> selectStockBillList(StockBill stockBill) {

        List<StockBill> stockBillList = getBaseMapper().selectStockBillList(stockBill);
        for (StockBill bill : stockBillList) {
            List<StockBillItem> stockBillItemList = stockBillItemService.getBaseMapper().selectList(new LambdaQueryWrapper<StockBillItem>()
                    .eq(StockBillItem::getBillId, bill.getId()));

            Integer num = 0;
            BigDecimal money = new BigDecimal("0");
            for (StockBillItem billItem : stockBillItemList) {
                GoodsStore good = goodsStoreService.getBaseMapper().selectOne(new LambdaQueryWrapper<GoodsStore>()
                        .eq(GoodsStore::getStoreId, bill.getStoreId())
                        .eq(GoodsStore::getGoodsId, billItem.getGoodsId()));
                num += billItem.getAmounts().intValue();
                money = money.add(billItem.getPrice().multiply(new BigDecimal(billItem.getAmounts())));
            }
            bill.setTotalNum(num);
            bill.setTotalMoney(money);
            Store store = storeService.getById(bill.getStoreId());
            bill.setStoreName(store.getStoreName());
            SysUser user = userService.selectUserById(bill.getOperatorId());
            bill.setOperatorName(user.getNickName());
        }
        return stockBillList;
    }

    @Override
    public String selectGoodListByStoreId(Long storeId) {
        List<Goods> goodList = new ArrayList<>();
        List<Long> goodIds = getBaseMapper().selectGoodIds(storeId);
        for (Long gId : goodIds) {
            Goods good = goodsService.getById(gId);
            goodList.add(good);
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(StockBill entity) {
        // 获取登录对象 设置为录入人
        // LoginUser loginUser = SecurityUtils.getLoginUser();
        entity.setOperatorId(SecurityUtils.getLoginUser().getUserId());
        // 获取当前时间 设置为录入时间
        entity.setOperateDate(new Date());

        // 根据仓库 id 查询库存信息
        List<GoodsStore> goodsStoreList = goodsStoreService.getBaseMapper().selectList(
                new LambdaQueryWrapper<GoodsStore>()
                        .eq(GoodsStore::getStoreId, entity.getStoreId())
        );

        // 根据仓库 id 删除库存信息中商品仓库关系表
        List<Long> goodIds = entity.getList().stream().map(StockBillItem::getGoodsId).collect(Collectors.toList());

        // 入库总数量
        Integer num = 0;
        // 入库商品总价格
        BigDecimal money = new BigDecimal("0");

        for (StockBillItem billItem : entity.getList()) {
            GoodsStore store = goodsStoreService.getOne(new LambdaQueryWrapper<GoodsStore>()
                    .eq(GoodsStore::getStoreId, entity.getStoreId())
                    .eq(GoodsStore::getGoodsId, billItem.getGoodsId()));

            num += billItem.getAmounts().intValue();
            money.add(billItem.getPrice().multiply(new BigDecimal(billItem.getAmounts())));
            GoodsStore goodsStore = new GoodsStore();
            goodsStore.setId(null);
            goodsStore.setGoodsId(billItem.getGoodsId());
            goodsStore.setStoreId(entity.getStoreId());
            if (store == null) {

                goodsStore.setAmounts(billItem.getAmounts());
                goodsStoreService.save(goodsStore);
            } else {
                goodsStoreService.getBaseMapper().delete(new LambdaQueryWrapper<GoodsStore>()
                .eq(GoodsStore::getGoodsId, billItem.getGoodsId())
                .eq(GoodsStore::getStoreId, entity.getStoreId()));
                goodsStore.setAmounts(billItem.getAmounts() + store.getAmounts());
                goodsStoreService.save(goodsStore);
            }
        }

        // 保存入库商品的数量
        entity.setTotalNum(num);
        entity.setTotalMoney(money);
        //stockBillMapper.deleteBatchGoodAndStoreRelation(entity.getStoreId(), goodIds);

        // 批量保存商品仓库关系表
        //stockBillMapper.batchInsertRelation(entity.getStoreId(), entity.getList());

        // 入库的状态默认是正常状态
        entity.setType(0);
        int insert = getBaseMapper().insert(entity);

        // 批量新增单据表
        stockBillMapper.batchInsertBillItem(entity.getId(), entity.getList());

        return insert > 0;
    }

    // 逻辑删除
    @Override
   @Transactional(rollbackFor = Exception.class)
    public boolean removeBatchByIds(Collection<?> list) {
        List<StockBill> stockBills = getBaseMapper().selectBatchIds((Collection<? extends Serializable>) list);
        for (StockBill stockBill : stockBills) {
            stockBill.setStatus(-1);
            List<StockBillItem> stockBillItems = stockBillItemService.getBaseMapper().selectList(new LambdaQueryWrapper<StockBillItem>()
                    .eq(StockBillItem::getBillId, stockBill.getId()));
            if (stockBillItems == null) {
                getBaseMapper().updateById(stockBill);
                return true;
            }
            for (StockBillItem stockBillItem : stockBillItems) {
                GoodsStore goodStore = goodsStoreService.getBaseMapper().selectOne(new LambdaQueryWrapper<GoodsStore>()
                        .eq(GoodsStore::getGoodsId, stockBillItem.getGoodsId())
                        .eq(GoodsStore::getStoreId, stockBill.getStoreId()));
                goodStore.setAmounts(goodStore.getAmounts() + stockBillItem.getAmounts());
                goodsStoreService.updateById(goodStore);
                // 删除出入库的记录
                stockBillItemService.getBaseMapper().deleteById(stockBillItem.getId());
            }
            getBaseMapper().updateById(stockBill);
        }
        return true;
    }

    @Override
    public StockBill getById(Serializable id) {

        // 通过前端传递过来的 id 查询出入库明细
        StockBill stockBill = super.getById(id);

        List<StockBillItem> stockBillItems = stockBillItemService.selectByStoreId(stockBill.getId());
        System.out.println(stockBillItems);
        stockBill.setList(stockBillItems);
        return stockBill;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteStockBill(StockBill entity) {

        // 获取登录对象 设置为录入人
        // LoginUser loginUser = SecurityUtils.getLoginUser();
        entity.setOperatorId(SecurityUtils.getLoginUser().getUserId());
        // 获取当前时间 设置为录入时间
        entity.setOperateDate(new Date());

        // 根据仓库 id 查询库存信息
        List<GoodsStore> goodsStoreList = goodsStoreService.getBaseMapper().selectList(
                new LambdaQueryWrapper<GoodsStore>()
                        .eq(GoodsStore::getStoreId, entity.getStoreId())
        );
        // 出库总数量
        Integer num = 0;
        // 出库商品总价格
        BigDecimal money = new BigDecimal("0");


        for (StockBillItem billItem : entity.getList()) {
            GoodsStore store = goodsStoreService.getOne(new LambdaQueryWrapper<GoodsStore>()
                    .eq(GoodsStore::getStoreId, entity.getStoreId())
                    .eq(GoodsStore::getGoodsId, billItem.getGoodsId()));

            num += billItem.getAmounts().intValue();
            money.add(billItem.getPrice().multiply(new BigDecimal(billItem.getAmounts())));
            GoodsStore goodsStore = new GoodsStore();
            goodsStore.setId(null);
            goodsStore.setGoodsId(billItem.getGoodsId());
            goodsStore.setStoreId(entity.getStoreId());
            if (store == null) {
                throw new ServiceException("仓库中没有该商品要出库");
            } else {
                if(store.getAmounts() < billItem.getAmounts()) {
                    throw new ServiceException("库存不足");
                }
                goodsStoreService.getBaseMapper().delete(new LambdaQueryWrapper<GoodsStore>()
                        .eq(GoodsStore::getGoodsId, billItem.getGoodsId())
                        .eq(GoodsStore::getStoreId, entity.getStoreId()));
                goodsStore.setAmounts(store.getAmounts() - billItem.getAmounts());
                goodsStoreService.save(goodsStore);
            }
        }

        // 保存出库商品的数量
        entity.setTotalNum(num);
        entity.setTotalMoney(money);

        // c出库的状态 1
        entity.setType(1);
        int insert = getBaseMapper().insert(entity);

        // 批量新增单据表
        stockBillMapper.batchInsertBillItem(entity.getId(), entity.getList());

        return insert;
    }
}
